package com.example.demo.listener;

import com.example.demo.config.Constants;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.nio.charset.Charset;

/**
 * 手动确认消息监听
 *
 * @param
 * @return
 * @date 2024/11/4 15:07
 * @author lililiang
 */
@Slf4j
@Component
public class ManualAckListener {
    @Resource
    private RabbitTemplate rabbitTemplate;


    @RabbitHandler
    @RabbitListener(ackMode = "MANUAL",
            bindings = {
                    @QueueBinding(
                            value = @Queue(value = Constants.QUEUE_MANUAL),
                            exchange = @Exchange(value = Constants.EXCHANGE_MANUAL),
                            key = {Constants.QUEUE_MANUAL}
                    )
            })
    public void onMessage1(Message message, Channel channel) throws IOException {
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        try {
            String strReceive = new String(message.getBody(), Charset.defaultCharset());
            log.info("queue-manualack 监听到数据:" + strReceive);
            if(strReceive.contains("10")){
                throw new IOException();
            }
            // 手动ack
            channel.basicAck(deliveryTag, false);
        } catch (Exception e) {
            log.info("queue-manualack 异常:");
            // 消费失败不再放入队列中
            channel.basicNack(deliveryTag, false,false);
            // 消费失败放入队列中
//            channel.basicNack(deliveryTag, false,true);
        }
    }

}
